const { app, BrowserWindow, Tray, Menu } = require('electron');
const path = require('path');

let mainWindow; // 将 mainWindow 定义在全局作用域中
let tray = null; // 确保 tray 也是全局变量，防止被垃圾回收
let forceQuit = false; // 添加一个标志来判断是否强制退出

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 604,
    height: 328,
    resizable: false,
    autoHideMenuBar: true,
    icon: path.join(__dirname, 'src', 'icon.ico'),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  mainWindow.loadFile('index.html');

  tray = new Tray(path.join(__dirname, 'src', 'icon.ico'));
  const contextMenu = Menu.buildFromTemplate([
    { label: '显示', click: () => { mainWindow.show(); } },
    { label: '退出', click: () => { 
        forceQuit = true; // 用户想要退出应用
        app.quit(); // 现在这会触发应用退出
     } }
  ]);
  tray.setToolTip('纯净时间');
  tray.setContextMenu(contextMenu);

  tray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show();
  });

  // 拦截关闭事件，改为隐藏窗口
  mainWindow.on('close', (event) => {
    if (!forceQuit) {
      event.preventDefault();
      mainWindow.hide();
    }
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  } else {
    mainWindow.show();
  }
});
